import React from "react";
import styles from './index.less';
import { Modal, Toast, Switch, Picker, InputItem } from 'antd-mobile';
import ReactDOM from 'react-dom';
import SeModal from '@/components/searchEmployee';
import QwcModal from '@/components/queryWbsCode';
import { getMastId } from '@/utils/tools';
import UserServices from '@/services/user';
import { requestSuccess, addHidden, removeHidden } from '@/utils/tools';

class tsModal extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isOutboundTrip: props.isOutboundTrip || false,
      isProjectCode: props.companyCode == '1100'?true:false,
      visible: true,
      editWbsInfo: props.editWbsInfo || false,
      message: props.message,
      content: props.content,
      success: props.success,
      cancel: props.cancel,
      dptrDay: props.dptrDay,
      rtnDay: props.rtnDay,
      allIdTypes: [],
      employees: '',
      chargeEmployees: '',
      wbsCode: '',
      wbsName: '',
      wbsManager: '',
      needInsurance: '',
      idType: '',
      idNumber: '',
      gender: '',
      nameInPassport: '',
      remark: ''
    };

    window.cordovaBackEvents.push(() => {
      this.handleCancel();
    });
  }

  componentDidMount(){
    addHidden();
    if(this.state.isOutboundTrip || this.state.isProjectCode){
      // 获取 idTypes
      const id = getMastId(); //{traMastId: xx}
      const text = `${Object.keys(id)[0]}=${Object.values(id)[0]}`
      UserServices.getAddTravellerLabel().then(res => {
        if(requestSuccess(res)){
          this.setState({
            allIdTypes: this.handleListLabel(res.data.allIDType),
            projectCodeList: this.handleListLabel(res.data.projectCodeList)
          })
        }
      })
    }
    if(this.state.editWbsInfo){
      console.log(this.state.editWbsInfo);
      this.setState({
        employees: this.state.editWbsInfo.empNo,
        chargeEmployees: this.state.editWbsInfo.chargeEmpNo
      })
    }
  }

  onChange = (value, key) => {
    this.setState({
      ...this.state,
      [key]: value
    })
  }

  handleListLabel = (list) => {
    return global._.map(list, item => {
      return {
        label: item,
        value: item
      }
    });
  }

  handleFormatData = () => {
    const id = getMastId();

    let extraData = {};
    if(this.state.isOutboundTrip && !this.state.editWbsInfo){
      extraData = {
        needInsurance: this.state.needInsurance?'YES':'NO',
        idType: this.state.idType,
        idNumber: this.state.idNumber,
        gender: this.state.gender,
        nameInPassport: this.state.nameInPassport,
        remark: this.state.remark
      }
    }
    let data = {
      ...id,
      trsMast: {
        dptrDay: global.moment(this.state.dptrDay).format('YYYY-MM-DD'),
        rtnDay: global.moment(this.state.rtnDay).format('YYYY-MM-DD')
      },
      traveler: {
        empNo: this.state.employees,
        chargeEmpNo: this.state.chargeEmployees,
        wbsCode: this.state.wbsCode,
        wbsName: this.state.wbsName,
        wbsManager: this.state.wbsManager,
        ...extraData
      }
    }

    if(this.state.editWbsInfo){
      console.log(this.state.editWbsInfo);
      data.travelerId = this.state.editWbsInfo.travelerId
    }

    return data;
  }

  handleSuccess = (e) => {
    // this.setState({
    //   visible: false,
    // });
    // this.state.success && this.state.success();
    const data = this.handleFormatData(this.state.values);
    const errorFn = (e) => {
      if(e){
        const message = e.message || 'Error';
        Toast.fail(message);
      }
    }
    UserServices.saveTraveler(data).then(res => {
      if(requestSuccess(res)){
        this.setState({
          visible: false,
        });
        removeHidden();
        console.log(res);
        this.state.success && this.state.success(res.data.allMobileTravelerList);
      }else{
        const errorInfo = global._.get(res, 'data.errorMessageList');
        errorFn(new Error(errorInfo))
      }
    }).then(errorFn)
  }

  handleCancel = (e) => {
    removeHidden();
    this.setState({
      visible: false,
    });
    this.state.cancel && this.state.cancel();
  }

  handleSelectedEmployee = (key)=>{
    if(this.state.editWbsInfo)return;
    SeModal.open({
      success: (result) => {
        console.log(result);
        this.setState({
          [key]: result.employees
        })
      },
      cancel: () => {

      }
    })
  }

  handleSelectedWbs = () => {
    QwcModal.open({
      success: (res) => {
        console.log(res);
        this.setState({
            wbsCode: res.posid,
            wbsName: res.post1,
            wbsManager: res.xubname
        })
      }
    })
  }

  render() {
    return (
      <Modal
        visible={this.state.visible}
        wrapClassName= {styles.tsModal}
      >
      <div>
        <div className={styles.info}>Travellers Setting</div>
        <div className={styles.list}>
          <div className={styles.item} onClick={() => this.handleSelectedEmployee('employees')}>
            <div className={styles.des}>*Traveller</div>
            <div className={styles.value}>{this.state.employees || 'Select'}</div>
          </div>
          <div className={styles.item} onClick={() => this.handleSelectedEmployee('chargeEmployees')}>
            <div className={styles.des}>Charge Employee</div>
            <div className={styles.value}>{this.state.chargeEmployees || 'Select'}</div>
          </div>
          {/*都是wbsCode字段*/}
          {
            this.state.isProjectCode
            ?
            <Picker data={this.state.projectCodeList} cols={1} onChange={(values) => this.onChange(values[0], 'wbsCode')}>
              <div className={styles.item}>
                <div className={styles.des}>Project Code</div>
                <div className={styles.value}>{this.state.wbsCode || 'Select'}</div>
              </div>
            </Picker>
            :
            <div className={styles.item} onClick={this.handleSelectedWbs}>
              <div className={styles.des}>WBS Code</div>
              <div className={styles.value}>{this.state.wbsCode || 'Select'}</div>
            </div>
          }
          {
            this.state.isOutboundTrip && !this.state.editWbsInfo
            ?
            <div>
              <div className={styles.item}>
                <div className={styles.des}>Insurance Needed</div>
                {/*
    （Choose 'NO'，Please provided insurance company name/ type/ expiration time in remark.）
                  */}
                <div className={styles.value}>
                  <Switch checked={this.state.needInsurance} onChange={(value) => this.onChange(value, 'needInsurance')}></Switch>
                </div>
              </div>
              <Picker data={this.state.allIdTypes} cols={1} onChange={(values) => this.onChange(values[0], 'idType')}>
                <div className={styles.item}>
                  <div className={styles.des}>*ID Type</div>
                  <div className={styles.value}>
                    {this.state.idType || 'Select'}
                  </div>
                </div>
              </Picker>
              <div className={styles.item}>
                <div className={styles.des}>ID Number</div>
                <div className={styles.value}>
                  <InputItem
                    clear
                    placeholder="click input"
                    value={this.state.idNumber}
                    onChange={(value) => this.onChange(value, 'idNumber')}
                  ></InputItem>
                </div>
              </div>
              <Picker data={[{label: 'Male', value: 'Male'}, {label: 'Female', value: 'Female'}]} cols={1} onChange={(values) => this.onChange(values[0], 'gender')}>
                <div className={styles.item}>
                  <div className={styles.des}>*Gender</div>
                  <div className={styles.value}>
                    {this.state.gender || 'Select'}
                  </div>
                </div>
              </Picker>
              <div className={styles.item}>
                <div className={styles.des}>Name In Passport</div>
                <div className={styles.value}>
                  <InputItem
                    clear
                    placeholder="click input"
                    value={this.state.nameInPassport}
                    onChange={(value) => this.onChange(value, 'nameInPassport')}
                  ></InputItem>
                {/*
                  （Attention : If you intend to use english name, please seperate your family name and your given name with '/' (e.g, Lee/David) And Please DO NOT USE any special characters except for '/'）
                  */}
                </div>
              </div>
              <div className={styles.item}>
                <div className={styles.des}>*Remark</div>
                <div className={styles.value}>
                  <InputItem
                    clear
                    placeholder="click input"
                    value={this.state.remark}
                    onChange={(value) => this.onChange(value, 'remark')}
                  ></InputItem>
                </div>
              </div>
            </div>
            :
            null
          }
        </div>
        <div className={styles.footerBtns}>
          <div onClick={this.handleSuccess}>Submit</div>
          <div onClick={this.handleCancel}>Close</div>
        </div>
      </div>
      </Modal>
    );
  }
}

export default {
  open(params){
    let div = document.createElement('div');
    document.body.appendChild(div);
    ReactDOM.render(React.createElement(tsModal, params), div);
  }
};
